<template>
  <el-dialog
    :title="formData.id ? '编辑部门' : '新增部门'"
    :visible="visible"
    width="50%"
    @close="closeFn"
  >
    <el-form
      ref="depForm"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="formData.name"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="formData.code"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="formData.manager"
          style="width: 80%"
          placeholder="请选择"
          @focus="getEmployeesSimple"
        >
          <el-option
            v-for="item in employeesList"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
          v-model="formData.introduce"
        />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeFn">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getEmployeesSimple } from "@/api/employees";
import { addDepartment, updateDepartment } from "@/api/department";
export default {
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    currentNode: {
      type: Object,
      required: true,
    },
    originDepts: {
      type: Array,
      require: true,
    },
  },
  data() {
    return {
      formData: {
        name: "",
        code: "",
        manager: "",
        introduce: "",
      },
      employeesList: [],
      formRules: {
        name: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
          { min: 1, max: 50, message: "要求1~50个字符哦~", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              // rule 是当前当前字段效验规则的信息，value就是此字段的值
              let isRepeat = false;
              if (this.formData.id) {
                // 先找出所有同级部门，去掉自己，再判断是否重复
                isRepeat = this.originDepts.filter(item => {
                    return item.pid === this.formData.pid && item.id !== this.formData.id
                }).some(item => item.name === value)
              } else {
                isRepeat = this.currentNode.children?.some(
                  (item) => item.name === value
                )
              }
              isRepeat ? callback(new Error("部门名称重复")) : callback();
            },
            trigger: "blur",
          },
        ],
        code: [
          { required: true, message: "部门编码不能为空", trigger: "blur" },
          { min: 1, max: 50, message: "要求1~50个字符哦~", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              const isRepeat = this.originDepts.some(
                // 在不是自己的情况下，code一样，才算重复
                (item) => item.code === value && item.id !== this.formData.id
              );
              isRepeat ? callback(new Error("部门编码重复")) : callback();
            },
            trigger: "blur",
          },
        ],
        manager: [
          { required: true, message: "部门负责人不能为空", trigger: "blur" },
        ],
        introduce: [
          { required: true, message: "部门介绍不能为空", trigger: "blur" },
          { min: 1, max: 50, message: "要求1~50个字符哦~", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    closeFn() {
      // 因为 resetFields 只能重置表单上的数据，非表单上的数据比如说id就不能重置了
      this.formData = {
        name: "",
        code: "",
        manager: "",
        introduce: "",
      };
      this.$refs.depForm.resetFields(); // 重置表单与校验
      this.$emit("update:visible", false);
    },
    async getEmployeesSimple() {
      this.employeesList = await getEmployeesSimple();
    },
    submit() {
      this.$refs.depForm.validate(async (isOk) => {
        // 如果没有通过效验，isOk 为 false
        if (isOk) {
          if (this.formData.id) {
            await updateDepartment(this.formData);
          } else {
            await addDepartment({ ...this.formData, pid: this.currentNode.id });
          }
          // 告诉父组件更新数据
          this.$emit("updateDeps");
          this.closeFn();
        }
      });
    },
  },
};
</script>

<style scoped>
.dialog-footer {
  width: 100%;
  display: inline-block;
  text-align: center;
}
</style>